<template>
  <div class="setting-container">
    <div class="setting-content">
      <div class="registerInfo">
        <div class="registerInfo-content">
          <el-form :label-position="labelPosition"
                   class="ruleForm"
                   label-width="100px"
                   :model="ruleForm"
                   :rules="rules"
                   ref="ruleForm">
            <el-form-item label="头像">
              <el-upload
                class="avatar-uploader-r"
                :action="domain"
                :data="qiniuToken"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="ruleForm.avatar" :src="ruleForm.avatar" class="avatar-r">
                <div class="avatar-r" v-else>
                  <div><i class="el-icon-plus avatar-uploader-r-icon"></i></div>
                  <div><span>上传头像</span></div>
                </div>
              </el-upload>
            </el-form-item>
            <div v-if="isShow">
              <el-form-item label="手机号" prop="mobile">
                <el-col :span="12">
                  <el-input v-model="ruleForm.mobile" placeholder="手机号" disabled></el-input>
                </el-col>
                <span @click="updatePhone" style="color:#3E909E;margin-left: 10px">修改手机号</span>
              </el-form-item>
              <div v-if="isPassword">
                <el-form-item label="密码" prop="password">
                  <el-col :span="12">
                    <el-input type="password" v-model="ruleForm.password" placeholder="密码" disabled></el-input>
                  </el-col>
                  <span @click="updatePassword" style="color:#3E909E;margin-left: 10px">修改密码</span>
                </el-form-item>
              </div>
              <div v-if="!isPassword">
                <el-form-item label="旧密码" prop="oldPassword">
                  <el-col :span="12">
                    <el-input type="password" v-model="ruleForm.oldPassword" placeholder="请输入原密码"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="新密码" prop="newPassword">
                  <el-col :span="12">
                    <el-input type="password" v-model="ruleForm.newPassword" placeholder="请输入新密码"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="确认密码" prop="alignPassword">
                  <el-col :span="12">
                    <el-input type="password" v-model="ruleForm.alignPassword" placeholder="请再次输入新密码"></el-input>
                  </el-col>
                </el-form-item>
              </div>
            </div>
            <div v-if="!isShow">
              <el-form-item label="手机号" prop="mobile">
                <el-col :span="12">
                  <el-input v-model="ruleForm.mobile" placeholder="手机号" ></el-input>
                </el-col>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <el-col :span="7">
                  <el-input v-model="ruleForm.code" placeholder="验证码" ></el-input>
                </el-col>
                <el-col :span="12">
                  <el-button class="border-btn" @click="smsClick" :disabled="disable" style="margin-left: 12px">{{codeStr}}</el-button>
                </el-col>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-col :span="12">
                  <el-input type="password" v-model="ruleForm.password" placeholder="密码" disabled></el-input>
                </el-col>
                <span @click="updatePassword" style="color:#3E909E;margin-left: 10px">修改密码</span>
              </el-form-item>
            </div>
          </el-form>
          <div style="float: right;margin-right: 20px;margin-bottom: 10px">
            <el-button class="border-btn" style="margin-left: 60px" @click="console()">取消</el-button>
            <el-button class="main-btn" type="primary" size="small" @click="submit()">确定</el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import {getQiniu, sendSms,updateMobile,updatePassword} from "../../../api/common";
  import {getInfo,updatePerson} from "../../../api/user";
  import {IsMobileExist} from "@/api/clinicManagement";
  export default {
    name: "setting",
    data() {
      //手机号校验
      var checkNumber = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入手机号"));
        } else {
          let regEn = /^1[3456789]\d{9}$/
          if (!regEn.test(value)) {
            callback(new Error('请输入正确电话号码'))
          }else if(value==this.mobile){
            callback();
          }else {
            this.disabled = false;
            this.isMobileExist(this.ruleForm.mobile, function (data) {
              if (data.state) {
                callback(new Error("该手机号已存在！"));
              } else {
                callback();
              }
            });
          }
        }
      }
      return {
        timer: null,
        disable:false,
        count: '',
        mobile:'',
        codeStr:'获取验证码',
        isShow:true,
        isPassword:true,
        domain: "http://upload.qiniu.com", // 七牛云的上传地址
        qiniuToken: {}, //上传到七牛的token
        activeName: 'first',
        labelPosition: 'right',
        ruleForm: {
          password: '******',
          mobile: '',
          code:'',
          oldPassword:'',
          newPassword:'',
          alignPassword:'',
        },
        disabled:false,
        rules: {
          mobile: [
            {  required: true,trigger: 'blur',validator:checkNumber}
          ],
          oldPassword: [
            { required: true, message: '请输入原密码', trigger: 'blur',},
            { min: 6, max: 12, message: '请输入6-12位的密码，可包含数字和字母', trigger: 'blur' }
          ],
          newPassword: [
            { required: true, message: '请输入新密码', trigger: 'blur',},
            { min: 6, max: 12, message: '请输入6-12位的密码，可包含数字和字母', trigger: 'blur' }
          ],
          alignPassword: [
            { required: true, message: '请确认密码', trigger: 'blur',},
            { min: 6, max: 12, message: '请输入6-12位的密码，可包含数字和字母', trigger: 'blur' }
          ],
        },
        updatePwd: 'first',
        real_name:'',
        gender:'',
      };
    },
    created() {
      this.real_name = this.$store.getters.userInfo.real_name
      this.gender = this.$store.getters.userInfo.gender
    },
    mounted() {
      // this.$store.getters.userInfo()
      console.log(this.$store.getters.userInfo)
      getInfo().then(res=>{
        if(res.code==200){
          console.log(res.data)
          this.mobile = res.data.mobile
          this.ruleForm.mobile = res.data.mobile
          this.ruleForm.avatar = res.data.avatar
        }
      })

    },
    computed: {},

    methods: {
      handleClick(tab, event) {
        console.log(tab, event);
      },
      //手机验证
      isMobileExist(mobile, callback) {
        let data={
          mobile:mobile
        }
        IsMobileExist(data).then((res) => {
          if (res.code === 200) {
            console.log(res.data)
            this.mobileExist = res.data.is_exits;
            if (this.mobileExist === true) {
              this.ruleForm.mobile = ''
              this.disabled = true
            }
            callback({state: this.mobileExist});
          }
        });
      },
      //获取验证码
      smsClick:function () {
        if (this.ruleForm.mobile == ""){
          this.$message.error('请输入手机号');
          return;
        }else{
          let data = {
            mobile:this.ruleForm.mobile,
            sms_key:'sms_auth'
          }
          sendSms(data).then((res)=>{
            if (res.code == 200){
              this.startTimer();
              this.$message({
                message: '验证码已发送',
                type: 'success'
              });
            }else {
              this.$message.error(res.msg);
            }
          })
        }
      },
      startTimer:function(){
        const TIME_COUNT = 60;
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.disable = true;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
              this.codeStr = this.count + "(s)"
            } else {
              this.codeStr = "重新发送"
              this.disable = false;
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000)
        }
      },
      //修改手机号
      updatePhone(){
        this.isShow=false
      },
      //修改密码
      updatePassword(){
        this.isPassword=false
        this.isShow = true
      },
      //取消更改
      console(){
        this.isShow = true
        this.isPassword = true
      },
      //提交修改
      submit(){
        if(this.isShow==false){
          let data = {
            mobile:this.ruleForm.mobile,
            valid_code:this.ruleForm.code,
          }
          updateMobile(data).then(res=>{
            if(res.code==200){
              this.$message.success('修改成功')
              this.isShow = true
              this.isPassword = true
            }else{
              this.$message.error(res.msg)
            }
          })
        }
        if(this.isShow==true&&this.isPassword==false){
          if (this.ruleForm.alignPassword != this.ruleForm.newPassword){
            this.$message.error('两次密码不一致');
            return;
          }
          let data = {
            mobile:this.ruleForm.mobile,
            old_pwd:this.ruleForm.oldPassword,
            new_pwd:this.ruleForm.newPassword,
          }
          updatePassword(data).then(res=>{
            if(res.code==200){
              this.$message.success('修改成功')
              this.isShow = true
              this.isPassword = true
            }else{
              this.$message.error(res.msg)
            }
          })
        }
      },
      // 上传用户图像成功
      handleAvatarSuccess(res) {
        this.ruleForm.avatar = this.QINIU.qiniu_url + "/" + res.key;
        let data={
          real_name:this.real_name,
          gender:this.gender,
          avatar:this.ruleForm.avatar
        }
        updatePerson(data).then(res=>{
          if(res.code==200){
            this.$message.success('更改成功')
          }
        })
      },
      beforeAvatarUpload(file) {
        const isJPGorPNG = file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPGorPNG) {
          this.$message.error("上传头像图片只能是 JPG,JPEG或PNG 格式!");
        }
        if (!isLt2M) {
          this.$message.error("上传头像图片大小不能超过 2MB!");
        }
        if (isJPGorPNG && isLt2M) {
          return getQiniu().then((res) => {
            this.qiniuToken = {
              token: res.data,
            };
          });
        } else {
          return isJPGorPNG && isLt2M
        }

      },
    },
  };
</script>
<style lang="scss" scoped>
  @import "@/assets/scss/clinicManagement/modules/setting.scss";
</style>
<style>
  .el-dialog__header {
    border-bottom: 1px solid #E6E6E6;
  }
  .avatar-uploader-r .el-upload {
    /*border: 1px dashed #d9d9d9;*/
    border-radius: 4px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    margin-top: -20px;
  }

  .avatar-uploade-r .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-r-icon {
    font-size: 28px;
    color: #8c939d;
    width: 50px;
    height: 50px;
    margin-top: 10px;
    line-height: 50px;
    text-align: center;
  }

  .avatar-r {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 50px;
  }
</style>
